package com.fqy.thread02.precise;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * User: fqy
 * Date: 2021/9/1
 * Time: 20:24
 * Describe:
 */
public class MyResource {
    private Integer flag = 1;

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 1){
                condition1.await();
            }
            //干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"coming...."+(i+1));
            }
            //精确通知
            flag = 2;
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 2){
                condition2.await();
            }
            //执行
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"coming...."+(i+1));
            }
            //通知
            flag = 3;
            condition3.signal();
        }finally {
            lock.unlock();
        }

    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 3){
                condition3.await();
            }
            //执行
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"coming...."+(i+1));
            }
            //通知
            flag = 1;
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }

}
